// 表头配置
const TABLE_HEADERS = {
    all: ['订单号', '订单类型', '订单详情', '价格', '状态', '操作'],
    hotel: ['订单号', '房间数', '联系人', '联系电话', '身份证', '价格', '状态', '酒店品牌', '操作'],
    scenic: ['订单号', '景点名称', '景点地址', '价格', '所在城市', '状态', '操作'],
    ticket: ['订单号', '类型', '票型', '出发城市', '到达城市', '出发时间', '价格', '状态', '操作']
};

// 工具函数
function formatPrice(value) {
    if (!value) return '0.00';
    return Number(value).toFixed(2);
}

function mapOrderStatus(status, orderType) {
    if (orderType === 'hotel') {
        const statusMap = {
            '待支付': '待付款',
            '未支付': '待付款',
            'null': '已完成',
            'NULL': '已完成',
            undefined: '已完成',
            '已支付': '已完成',
            '已完成': '已完成',
            '已取消': '已取消'
        };
        return statusMap[status] || status || '已完成';
    }
    return '已完成';
}

function getStatusClass(status) {
    const statusClasses = {
        '待付款': 'text-warning',
        '已付款': 'text-success',
        '已完成': 'text-success',
        '已取消': 'text-danger'
    };
    return statusClasses[status] || '';
}

// 创建表头
function createTableHeader(type) {
    const headers = TABLE_HEADERS[type] || TABLE_HEADERS.all;
    let headerHtml = '<tr>';
    for (let i = 0; i < headers.length; i++) {
        headerHtml += '<th>' + headers[i] + '</th>';
    }
    headerHtml += '</tr>';
    return headerHtml;
}

// 订单类型映射
function mapOrderType(type) {
    const typeMap = {
        'hotel': '酒店订单',
        'scenic': '景点订单',
        'ticket': '车票订单'
    };
    return typeMap[type] || type;
}

// 创建订单详情
function createOrderDetails(order) {
    let details = [];
    if (order.hotel) {
        details = [
            '房间数: ' + (order.hotel.roomNum || ''),
            '联系人: ' + (order.hotel.contactName || ''),
            '电话: ' + (order.hotel.contactPhone || ''),
            '身份证: ' + (order.hotel.idCard || ''),
            '品牌: ' + (order.hotel.brand || '')
        ];
    } else if (order.scenicSpot) {
        details = [
            '景点名称: ' + (order.scenicSpot.scenicName || ''),
            '地址: ' + (order.scenicSpot.scenicAddress || ''),
            '城市: ' + (order.scenicSpot.city || '')
        ];
    } else if (order.tickets) {
        details = [
            '类型: ' + (order.tickets.type || ''),
            '票型: ' + (order.tickets.ticketType || ''),
            '出发城市: ' + (order.tickets.departure_city || ''),
            '到达城市: ' + (order.tickets.arrival_city || ''),
            '出发时间: ' + (order.tickets.departure_time || '')
        ];
    }
    return details.join('<br>');
}

// 创建操作按钮
function createOperationButtons(orderId, orderType, status, price) {
    let buttons = '';

    if (orderType === 'hotel' && status === '待付款') {
        const cleanPrice = parseFloat(price) || 0;
        buttons += '<button type="button" ' +
            'class="btn btn-primary btn-sm pay-order-btn me-2" ' +
            'data-order-id="' + orderId + '" ' +
            'data-order-type="' + orderType + '" ' +
            'data-order-price="' + cleanPrice.toFixed(2) + '">' +
            '去支付' +
            '</button>';

        // 添加取消按钮
        buttons += '<button type="button" ' +
            'class="btn btn-danger btn-sm delete-order-btn">' +
            '取消' +
            '</button>';

        return buttons;
    }

    return '<button type="button" ' +
        'class="btn btn-danger btn-sm delete-order-btn">' +
        '删除' +
        '</button>';
}

// 创建订单行
function createOrderRow(order, type) {

    let orderId, orderType, price, status;

    if (order.hotel) {
        orderId = 'H' + order.hotel.id;
        orderType = 'hotel';
        price = parseFloat(order.hotel.price) || 0;
        status = mapOrderStatus(order.hotel.status, 'hotel');
    } else if (order.scenicSpot) {
        orderId = 'S' + order.scenicSpot.id;
        orderType = 'scenic';
        price = parseFloat(order.scenicSpot.price) || 0;
        status = '已完成';
    } else if (order.tickets) {
        orderId = 'T' + order.tickets.id;
        orderType = 'ticket';
        price = parseFloat(order.tickets.price) || 0;
        status = '已完成';
    }

    let cells = [];
    let rowHtml = '<tr data-order-id="' + orderId + '" data-order-type="' + orderType + '">';

    if (type === 'all') {
        cells = [
            orderId,
            mapOrderType(orderType),
            createOrderDetails(order),
            '￥' + formatPrice(price),
            '<span class="' + getStatusClass(status) + '">' + status + '</span>',
            createOperationButtons(orderId, orderType, status, price)
        ];
    } else if (orderType === 'hotel') {
        cells = [
            orderId,
            order.hotel.roomNum || '',
            order.hotel.contactName || '',
            order.hotel.contactPhone || '',
            order.hotel.idCard || '',
            '￥' + formatPrice(price),
            '<span class="' + getStatusClass(status) + '">' + status + '</span>',
            order.hotel.brand || '',
            createOperationButtons(orderId, orderType, status, price)
        ];
    } else if (orderType === 'scenic') {
        cells = [
            orderId,
            order.scenicSpot.scenicName || '',
            order.scenicSpot.scenicAddress || '',
            '￥' + formatPrice(price),
            order.scenicSpot.city || '',
            '<span class="' + getStatusClass(status) + '">' + status + '</span>',
            createOperationButtons(orderId, orderType, status, price)
        ];
    } else if (orderType === 'ticket') {
        cells = [
            orderId,
            order.tickets.type || '',
            order.tickets.ticketType || '',
            order.tickets.departure_city || '',
            order.tickets.arrival_city || '',
            order.tickets.departure_time || '',
            '￥' + formatPrice(price),
            '<span class="' + getStatusClass(status) + '">' + status + '</span>',
            createOperationButtons(orderId, orderType, status, price)
        ];
    }

    for (let i = 0; i < cells.length; i++) {
        rowHtml += '<td>' + cells[i] + '</td>';
    }
    rowHtml += '</tr>';

    return rowHtml;
}

// 处理支付请求
function handlePayment(orderId, orderType, price) {

    if (!orderId || !orderType || !price) {
        alert('订单信息不完整');
        return;
    }

    const form = document.createElement('form');
    form.method = 'POST';
    // 添加项目上下文路径
    form.action = window.location.pathname.substring(0, window.location.pathname.indexOf('/', 1)) + '/alipay/pay';

    const inputs = {
        orderId: orderId.substring(1),
        orderType: orderType,
        money: price.toString()
    };

    for (let name in inputs) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = name;
        input.value = inputs[name];
        form.appendChild(input);
    }

    document.body.appendChild(form);
    form.submit();
}

// 删除订单
function deleteOrder(orderId, orderType) {
    const numericId = orderId.substring(1);
    const orderTypeMap = {
        'hotel': '酒店',
        'scenic': '景点',
        'ticket': '车票'
    };

    const typeForBackend = orderTypeMap[orderType] || orderType;

    if (!confirm('确定要删除这个' + typeForBackend + '订单吗？')) {
        return;
    }

    $.ajax({
        url: 'deleteOrder',
        type: 'POST',
        data: {
            orderId: numericId,
            orderType: typeForBackend
        },
        success: function (response) {
            const result = typeof response === 'string' ? JSON.parse(response) : response;
            if (result.success) {
                alert('删除成功');
                loadOrders($('.order-tabs .tab-btn.active').data('type'));
            } else {
                alert('删除失败：' + (result.message || '未知错误'));
            }
        }
    });
}

// 加载订单数据
function loadOrders(type) {
    const tableBody = $('#orderTableBody');
    tableBody.html('<tr><td colspan="9" class="text-center">加载中...</td></tr>');

    $.ajax({
        url: 'orders',
        type: 'POST',
        data: {action: type + 'Orders'},
        dataType: 'json',
        success: function (response) {
            if (response.success && response.data) {
                let rowsHtml = '';
                for (let i = 0; i < response.data.length; i++) {
                    rowsHtml += createOrderRow(response.data[i], type);
                }
                tableBody.html(rowsHtml || '<tr><td colspan="9" class="text-center">暂无订单数据</td></tr>');
            } else {
                tableBody.html('<tr><td colspan="9" class="text-center text-danger">暂无订单数据</td></tr>');
            }
        },
        error: function () {
            tableBody.html('<tr><td colspan="9" class="text-center text-danger">加载失败，请刷新重试</td></tr>');
        }
    });
}

// 初始化订单管理
function initializeOrderManagement() {
    const tableHeader = createTableHeader('all');
    $('.order-content table thead').html(tableHeader);

    $('.order-tabs .tab-btn').off('click').on('click', function () {
        const type = $(this).data('type');
        $('.order-tabs .tab-btn').removeClass('active');
        $(this).addClass('active');
        const newHeader = createTableHeader(type);
        $('.order-content table thead').html(newHeader);
        loadOrders(type);
    });

    loadOrders('all');
}

// 页面加载完成后初始化
$(document).ready(function () {
    const urlParams = new URLSearchParams(window.location.search);
    const paymentStatus = urlParams.get('payment');

    if (paymentStatus) {
        switch (paymentStatus) {
            case 'success':
                alert('支付成功！');
                break;
            case 'error':
                alert('支付失败，请稍后重试或联系客服');
                break;
            case 'invalid':
                alert('支付验证失败，请联系客服');
                break;
        }
        window.history.replaceState({}, document.title, window.location.pathname);
    }

    $.ajax({
        url: '/GetStatusCount',
        type: 'POST',
        dataType: 'text',
        success: function (response) {
            $('.stat-value').first().text(response);
        }
    });

    const orderManagement = $('#my-orders');
    if (orderManagement.length) {
        initializeOrderManagement();

        // 支付按钮事件处理
        $(document).on('click', '.pay-order-btn', function (e) {
            e.preventDefault();
            const $button = $(this);

            const orderId = $button.data('orderId');
            const orderType = $button.data('orderType');
            const price = $button.data('orderPrice');


            if (!orderId || !orderType || !price) {
                alert('订单信息不完整，请刷新页面重试');
                return;
            }

            handlePayment(orderId, orderType, price);
        });

        // 删除按钮事件处理
        $(document).on('click', '.delete-order-btn', function (e) {
            e.preventDefault();
            const $row = $(this).closest('tr');
            const orderId = $row.data('orderId');
            const orderType = $row.data('orderType');

            if (!orderId || !orderType) {
                alert('无效的订单信息');
                return;
            }

            deleteOrder(orderId, orderType);
        });
    }
    $('.stat-value').first().css('cursor', 'pointer').click(function () {
        window.location.hash = 'my-orders';

        $('#my-orders').show();

        $('#my-ly').hide();
    })
});

// 导出全局函数
window.initializeOrderManagement = initializeOrderManagement;
window.deleteOrder = deleteOrder;